from tkinter import *
from tkinter import filedialog
from tkinter import ttk
from threading import Thread
from sql import sqlseverDB
from mini_tools.cjjtool import *
from mini_tools.myexcel import *
from mini_tools.mytools import *
import tkinter.messagebox as messagebox
import openpyxl,re,time,copy,concurrent.futures

class DataGLFra(Frame):
    def __init__(self,master=None):
        Frame.__init__(self,master)
        ADDTaskFrame(self).pack(fill=X,padx=2,pady=2)


class ADDTaskFrame(Frame):

    def __init__(self,master=None):
        Frame.__init__(self, master)

        self.ms = sqlseverDB('{SQL Server}', SQL_SERVER, 'SuMaiTongPol', SQL_USER, SQL_PWD)
        self.rwCount=StringVar()
        self.rwCount.set(f'正在获取群控任务数据...')
        self.createWidgets()
        Thread(target=self.getcount).start()

    def createWidgets(self):

        f0=Frame(self)
        f0.pack(fill=X,padx=2,pady=2)
        Label(f0, text='增加群控任务', fg="white", bg="#007FFF",font=("微软雅黑", 13),width=50).pack(fill=X,padx=5)

        f1=Frame(self)
        f1.pack(fill=X,padx=2,pady=2)
        f01=Frame(f1)
        f01.pack(pady=2,fill=X,padx=2)
        Label(f01, textvariable=self.rwCount,fg='red').pack(side=LEFT,padx=2, pady=2)

        f00=Frame(f1)
        f00.pack(pady=2,fill=X,padx=2)
        Label(f00, text='输入任务名字:').pack(side=LEFT, padx=2, pady=2)
        self.rwNameIpt = Entry(f00)
        self.rwNameIpt.pack(side=LEFT, padx=2, pady=2)

        Label(f00,text='任务平台:').pack(side=LEFT, padx=2, pady=2)
        self.PTSelect = ttk.Combobox(f00,width=10,state='readonly')
        self.PTSelect['value']=['印尼虾皮','波兰阿里狗','菲律宾虾皮','泰国虾皮']
        self.PTSelect.pack(side=LEFT, padx=2, pady=2)
        self.PTSelect.current(0)

        self.mbv=['虾皮任务(采集)','虾皮任务(采集2)','虾皮任务(操作)','虾皮大数据筛选','采集功能','DeepSeek','其他任务']
        Label(f00,text='放置面板:').pack(side=LEFT, padx=2, pady=2)
        self.GTMBSelect = ttk.Combobox(f00,width=15,state='readonly')
        self.GTMBSelect['value']=self.mbv
        self.GTMBSelect.pack(side=LEFT, padx=2, pady=2)
        self.GTMBSelect.current(0)

        f01=Frame(f1)
        f01.pack(pady=2,fill=X,padx=2)


        Label(f01,text='控制字段(is开头):').pack(side=LEFT, padx=2, pady=2)
        self.IsZdIpt = Entry(f01,width=10)
        self.IsZdIpt.pack(side=LEFT, padx=2, pady=2)

        Label(f01,text='额外参数值(选填):').pack(side=LEFT, padx=2, pady=2)
        self.ExtraIpt = Entry(f01,width=8)
        self.ExtraIpt.pack(side=LEFT, padx=2, pady=2)

        f02=Frame(f1)
        f02.pack(pady=2,fill=X,padx=2)

        self.btn_add=Button(f02,text='增加任务',fg='#ffffff',bg='green',command=lambda:Thread(target=self.add_task).start(),width=15)
        self.btn_add.pack(side=LEFT, padx=2, pady=2)


    def getcount(self):
        while True:
            try:
                rs=self.ms.ExecQuery('''SELECT gtName from task where position!=-1''')
                mb_str=''
                rw_mvs=[r[0] for r in rs]
                for mb_name in self.mbv:
                    mb_count=rw_mvs.count(mb_name)
                    mb_str+=f'{mb_name}:{mb_count}个 , '
                self.rwCount.set(mb_str)
                time.sleep(10)
            except Exception as e:
                print(e)
    
    def add_task(self):
        
        rw_name=self.rwNameIpt.get().strip()
        is_zd=self.IsZdIpt.get().strip()
        if not rw_name:
            messagebox.showerror('提示','请先输入正确任务信息')
            return
        self.btn_add.config(state=DISABLED)
        rw_fun_name=None
        gt_name=self.GTMBSelect.get()
        rs= self.ms.ExecQuery('select count(*) from task where tName=? ',(rw_name,))
        if rs[0][0]>0:
            print(f'任务名:《{rw_name}》重复,请重新设置')
            messagebox.showinfo('提示',f'任务名:《{rw_name}》重复,请重新设置')
            self.btn_add.config(state=NORMAL)
            return
        if gt_name!='其他任务':
            rs=self.ms.ExecQuery('select count(*) from task where gtName=? and position!=-1',(gt_name,))
            max_pos=rs[0][0]
            if max_pos>=9:
                print(f'gt面板:{gt_name},任务已经达到9个,请切换面板')
                messagebox.showinfo('提示',f'gt面板:{gt_name},任务已经达到9个,请切换面板')
                self.btn_add.config(state=NORMAL)
                return
            now_pos=1
        else:
            now_pos=-1
            
        extra_param=self.ExtraIpt.get().strip()
        extra_param =extra_param if extra_param else None
        pt_select=self.PTSelect.get()
        if pt_select=='印尼虾皮':
            shop_class='shop'
            pt='虾皮'
            houtai='HouTai'
        elif pt_select=='波兰阿里狗':
            shop_class='alshop'
            pt='波兰'
            houtai='HouTai_ALG'
        elif pt_select=='菲律宾虾皮':
            shop_class='phshop'
            pt='菲律宾虾皮'
            houtai='ShopeePHAccount'
        elif pt_select=='泰国虾皮':
            shop_class='thshop'
            pt='泰国虾皮'
            houtai='HouTai_TH'
        

        sql_list=[]
        zds=['tName','ShopClass','pt','iszd','FuncName','extraParam','gtName','position']
        params=[rw_name,shop_class,pt,is_zd,rw_fun_name,extra_param,gt_name,now_pos]
        zdstr=','.join(zds)
        wstr=','.join(['?' for _ in params])
        sql_str=f'insert task({zdstr}) values({wstr})'
        sql_list.append([sql_str,params])
        cols=self.ms.GetCol('HouTai')
        clos_lower=[c.lower() for c in cols]
        if is_zd and is_zd.lower() not in clos_lower:
            sql_list.append([f'alter table {houtai} add {is_zd} int default 0',None])
            sql_list.append([f'update {houtai} set {is_zd}=0',None])
        aff=self.ms.ExecTransaction(sql_list)
        if aff>0:
            print(f'成功创建任务《{rw_name}》,影响行数:{aff}')
            messagebox.showinfo('提示',f'成功创建任务《{rw_name}》,影响行数:{aff}')
        else:
            print(f'创建任务《{rw_name}》,失败')
            messagebox.showinfo('提示',f'创建任务《{rw_name}》,失败')
        self.btn_add.config(state=NORMAL)

# import tkinter
# list_win=tkinter.Tk()
# list_win.wm_geometry("800x650")
# list_win.title('数据管理')
# DataGLFra(list_win).pack(fill=X,padx=3,pady=3)
# list_win.mainloop()